<?php
/**
 * 合同管理：工程变更单控制器
 *@author ZhouYP
 */
namespace Admin\Controller;
use Common\Controller\AuditbaseController;
class EngineeringChangeOrderController extends AuditbaseController{

	    public function _initialize() {
        parent::_initialize();
        $this->deal_model = D("Common/EngineeringChangeOrder");

        $this->check = array('code');

        // 当前审批流程
        $this->function = "contract";
        $this->subfunction = "5";
    }

    /**
     * 主页
     */
    public function index() {
        $isAudit = ",(
		CASE
			WHEN audit_status != 1 THEN 2
			WHEN audit_level = 2 AND (SELECT role_id FROM ".C('DB_PREFIX')."users WHERE id = '".session('ADMIN_ID')."') = '3' AND d.add_department = ".session('deptid')." THEN 1
			WHEN audit_level = 7 AND (SELECT role_id FROM ".C('DB_PREFIX')."users WHERE id = '".session('ADMIN_ID')."') = '2' AND d.put_forward_department = ".session('deptid')." THEN 1
			WHEN audit_level = 8 AND (SELECT role_id FROM ".C('DB_PREFIX')."users WHERE id = '".session('ADMIN_ID')."') = '3' AND d.put_forward_department = ".session('deptid')." THEN 1
			WHEN audit_level > 2 AND audit_status = 1 AND audit_level % 2 = 1 
					AND (SELECT role_id FROM ".C('DB_PREFIX')."users WHERE id = '".session('ADMIN_ID')."') = '2'
					AND (
						SELECT 2 * fd.`level` + 1
						FROM ".C('DB_PREFIX')."audit_flow_dept fd
						LEFT JOIN ".C('DB_PREFIX')."audit_flow f ON fd.flow_id = f.id
						WHERE f. FUNCTION = '".$this->function."' AND f.subfunction = '".$this->subfunction."' AND fd.department_id = ".session('deptid')." ) = d.audit_level
			THEN 1
			WHEN audit_level > 2 AND audit_status = 1 AND audit_level % 2 = 0
					AND (SELECT role_id FROM ".C('DB_PREFIX')."users WHERE id = '".session('ADMIN_ID')."') = '3'
					AND (
						SELECT 2 * fd.`level` + 2
						FROM ".C('DB_PREFIX')."audit_flow_dept fd
						LEFT JOIN ".C('DB_PREFIX')."audit_flow f ON fd.flow_id = f.id
						WHERE f. FUNCTION = '".$this->function."' AND f.subfunction = '".$this->subfunction."' AND fd.department_id = ".session('deptid').") = d.audit_level
			THEN 1
			ELSE 2
		END
		) as isaudit";
		
		/**搜索条件**/
		$where = "d.is_deleted <> 1 AND (
			d.add_user = '".session('ADMIN_ID')."'
			OR 1 = '".session('ADMIN_ID')."'
			OR (
				d.audit_status != 3 AND 
				(
					(audit_level = 2 AND (SELECT department_id FROM hzzy_users WHERE id = '".session('ADMIN_ID')."') = d.add_department AND (SELECT role_id FROM hzzy_users WHERE id = '".session('ADMIN_ID')."') = '3')
					OR(
						audit_level = 7
						AND (
							SELECT department_id
							FROM hzzy_users
							WHERE id = '".session('ADMIN_ID')."'
						) = d.put_forward_department
						AND (
							SELECT role_id
							FROM hzzy_users
							WHERE id = '".session('ADMIN_ID')."'
						) = '2'
					)
					OR(
						audit_level = 8
						AND (
							SELECT department_id
							FROM hzzy_users
							WHERE id = '".session('ADMIN_ID')."'
						) = d.put_forward_department
						AND (
							SELECT role_id
							FROM hzzy_users
							WHERE id = '".session('ADMIN_ID')."'
						) = '3'
					)
					OR (
						audit_level > 2 AND audit_level < 7
						AND 
							CASE audit_level%2
							WHEN 1 THEN 
								(SELECT role_id FROM hzzy_users WHERE id = '".session('ADMIN_ID')."') = '2' 
								AND (SELECT 2 * fd.`level` + 1 FROM hzzy_audit_flow_dept fd 
									LEFT JOIN hzzy_audit_flow f ON fd.flow_id = f.id 
									WHERE f.function='".$this->function."' AND f.subfunction='".$this->subfunction."' AND fd.department_id = ".session('deptid')." ) = d.audit_level
							ELSE 
								(SELECT role_id FROM hzzy_users WHERE id = '".session('ADMIN_ID')."') = '3' 
								AND (SELECT 2 * fd.`level` + 2 FROM hzzy_audit_flow_dept fd 
								LEFT JOIN hzzy_audit_flow f ON fd.flow_id = f.id 
								WHERE f.function='".$this->function."' AND f.subfunction='".$this->subfunction."' AND fd.department_id = ".session('deptid')." ) = d.audit_level
							END
					)
				)
			)
			OR (
				d.audit_status = 3 AND (
					(SELECT department_role FROM hzzy_department WHERE id='".session('deptid')."') <= (SELECT department_role
					FROM hzzy_audit_flow_dept fd 
					LEFT JOIN hzzy_audit_flow f ON fd.flow_id = f.id 
					LEFT JOIN hzzy_department dp ON dp.id = fd.department_id 
					WHERE f.function='".$this->function."' AND f.subfunction='".$this->subfunction."'
					ORDER BY fd.`LEVEL` DESC
					LIMIT 1)
				) OR (
					'".session('ADMIN_ID')."' IN (SELECT add_user FROM hzzy_audit_history WHERE function='".$this->function."' AND subfunction='".$this->subfunction."' AND table_id = d.id)
				)
			)
		)";
		
		$count = $this->deal_model->alias("d")->where($where)->count();
        $page = $this->page($count, 20);
		
		$results = $this->deal_model->alias("d")
            ->field('d.*,u.real_name,((f. LEVEL + 1) * 2 + 2) as `level`,h.time,DATE_ADD(h.time, INTERVAL 7 DAY) as newtime'.$isAudit)
            ->join(array(
                ' LEFT JOIN '.C('DB_PREFIX').'users u ON d.add_user = u.id',
				' LEFT JOIN '.C('DB_PREFIX').'audit_flow f ON f.function = \''.$this->function."' AND f.subfunction='".$this->subfunction."'",
				' LEFT JOIN (SELECT table_id,MAX(add_time) as time FROM '.C('DB_PREFIX').'audit_history WHERE `function` = \''.$this->function.'\' AND subfunction = \''.$this->subfunction.'\' GROUP BY table_id) as h ON h.table_id = d.id'
            ))
            ->where($where)
            ->order("d.add_time DESC")
            ->limit($page->firstRow, $page->listRows)
            ->select();
		//exit($this->deal_model->getLastSql());
        $this->assign("page", $page->show('Admin'));
        $this->assign("results",$results);
        
        $this->display();
    }

    public function add(){
        $data=M("department");
        $where ="department_role = 4 and is_deleted = 0";
        $department=$data->where($where)->select();
        $this->assign("Department",$department);

        $depts = $data->field("id,department_name")->where(array('is_deleted' => array('neq', 1),'department_role' =>array('elt',3) ))->select();
        $this->assign("depts", $depts);

        $this->display();   
    }

	public function view(){
		// 获取基础数据
		$id = I('get.id',0,'intval');
        $result = $this->deal_model->where(array("id"=>$id))->find();
        $this->assign("result", $result);
				
		$isAudit = '1';
		// 验证当前登录人是否有审批权限
		if(($result['audit_level'] == 2 && $result['add_department'] == session('deptid') && session('Role') == 3)
			|| ($result['audit_level'] == 7 && $result['put_forward_department'] == session('deptid') && session('Role') == 2)
			|| ($result['audit_level'] == 8 && $result['put_forward_department'] == session('deptid') && session('Role') == 3)){
			$isAudit = '2';
		} elseif($result['audit_level'] > 2 && $result['audit_level'] < 7) {
			// 查询当前审批部门
			$auditdept = $this->auditFlowModel->alias("a")
							->field("d.department_id")
							->join(array(
								' LEFT JOIN '.C('DB_PREFIX').'audit_flow_dept d ON d.flow_id = a.id'
							))
							->where(array(
								'a.function' 	=> $this->function,
								'a.subfunction'	=> $this->subfunction,
								'd.`level`'		=> intval(($result['audit_level'] - 1)/2)
							))
							->find();
			if((intval($result['audit_level'])%2 == 1 && $auditdept['department_id'] == session("deptid") && session('Role') == 2)
					|| (intval($result['audit_level'])%2 == 0 && $auditdept['department_id'] == session("deptid") && session('Role') == 3)){
				$isAudit = '2';
			}
		}
		$this->assign("isAudit", $isAudit);
		
		// 循环查询审核意见
		$auditResult = array();
		for($i = 1; $i < 8; $i += 2){
			$auditResult[$i] = $this->auditHistoryModel->where(array('function' => $this->function, 'subfunction' => $this->subfunction, 'audit_level' => $i, 'table_id' => $id))->order("add_time DESC")->find();
		}
		$this->assign("audit", $auditResult);
		// 判断最终状态是否为驳回
		if($result['audit_status'] == '2'){
			// 查询驳回原因
			$returnMsg = $this->auditHistoryModel->where(array('function' => $this->function, 'subfunction' => $this->subfunction, 'table_id' => $id))->order("add_time DESC")->find();
			$this->assign("reject", $returnMsg);
		}		
		// 验证审批权限
		$this->display();
	}
	
	
	// 保存审批意见
	public function audit_post(){
		if(IS_POST){
			$url = U(CONTROLLER_NAME.'/'.(I('get.fun') != NULL ? I('get.fun') : 'index'));
            $data = array_merge($_POST, $this->auditAdd());
            if ($this->auditHistoryModel->create()!==false) {
                $result = $this->auditHistoryModel->add($data);
                if ($result!==false) {					
					// 修改修改主表当前处理层级+1
					$update = array(
						'id'			=> $data['table_id'],
						'audit_level'	=> $data['audit_status'] == 1 ? intval($data['audit_level']) + 1 : intval($data['audit_level']) - 1,
						'audit_status'	=> $data['audit_status'] == 2 ? 2 : (8 == intval($data['audit_level']) ? 3 : 1)
					);
					$update = array_merge($_POST, $update);
					$this->deal_model->save($update);
					
                    $this->success("保存成功！", $url);
                } else {
                    $this->error("保存失败！");
                }
            } else {
                $this->error($this->auditHistoryModel->getError());
            }
        }
	}
	//分配权限页面
    public function distribution(){
        $level = $_GET['level'];
        //var_dump($level);
        $this->assign("level", $level);
        $this->distribution_base();
    }
}
?>